<template>
	<a-table
		:columns="_columns"
		:dataSource="items"
		row-key="srfkey"
		:sticky="items.length > 0"
		:custom-row="customRow"
		:show-header="showHeader"
		table-layout="fixed"
		:scroll="scrollOptions"
		:loading="loading"
		:pagination="paging ? initPaging(props) : false"
		:row-selection="rowSelection"
		@change="handleGridChange"
		@resize-column="handleResizeColumn"
	>
		<template #headerCell="{ title, column }">
			<slot
				v-if="hasSlot('header')"
				:title="title"
				:column="column"
				name="header"
			></slot>
			<AppGridColumnHeader
				v-else
				:column="column"
				:context="context"
				:viewParams="viewParams"
			/>
		</template>
		<template #bodyCell="{ column, text, record, index }">
			<slot
				v-if="hasSlot('body')"
				:text="text"
				:column="column"
				:record="record"
				:index="index"
				name="body"
			></slot>
			<slot
				v-else-if="hasSlot(column.pluginCode)"
				:rowData="{ column, text, record, index }"
				:name="column.pluginCode"
			/>
			<AppGridColumn
				v-else
				:text="text"
				:column="column"
				:record="record"
				:index="index"
				:context="context"
				:viewParams="viewParams"
				@handle-action="(detail, event) => handleAction(detail, record, event)"
			/>
		</template>
		<template #emptyText>
			<AppEmptyDataTip
				:emptyText="$t(emptyTextPSLanguageRes, emptyText)"
			></AppEmptyDataTip>
		</template>
		<template #summary v-if="enableAgg">
			<a-table-summary fixed>
				<a-table-summary-row>
					<a-table-summary-cell></a-table-summary-cell>
					<a-table-summary-cell
						v-for="column in _columns"
						:key="column.dataItemName"
					>
						{{ aggData[column.dataItemName] }}
					</a-table-summary-cell>
				</a-table-summary-row>
			</a-table-summary>
		</template>
	</a-table>
</template>
<script setup lang="ts">
import { gridProps, getColumnTotalWidth, initPaging } from './grid';
import AppGridColumn from './components/grid-column.vue';
import AppGridColumnHeader from './components/grid-column-header.vue';
import AppEmptyDataTip from '@/components/common/empty-data-tip/src/empty-data-tip.vue';
import { IParam } from '@/core';
const props = defineProps(gridProps);
const emit = defineEmits<{
	(name: 'selectionChange', selections: IParam[]): void;
	(name: 'rowClick', row: IParam, event: MouseEvent): void;
	(name: 'rowDbClick', row: IParam, event: MouseEvent): void;
	(name: 'pageSizeChange', size: number): void;
	(name: 'pageChange', currentPage: number): void;
	(name: 'sortChange', field: string, dir: 'asc' | 'desc' | ''): void;
	(name: 'actionClick', logic: IParam, data: IParam, event: MouseEvent): void;
}>();

const hasSlot = (name: string): boolean => {
	return !!useSlots()[name];
};

const selectedKeys = computed<string[]>(() => {
	return props.selections.map((select: IParam) => select.srfkey) || [];
});
const _columns = ref<IParam>([]);
watch(
	() => props.columns,
	() => {
		_columns.value.length = 0;
		props.columns.forEach((column: IParam) => {
			if (!column.hideDefault && !column.hiddenDataItem) {
				_columns.value.push(column);
			}
		});
	},
	{ immediate: true }
);
//  设置定时器防抖
let timer: any = null;
//  表格行选择配置项
const rowSelection: any = {
	columnWidth: 50,
	selectedRowKeys: selectedKeys,
	checkStrictly: false,
	hideSelectAll: props.singleSelect,
	onSelect: (record: IParam, selected: boolean, selectedRows: IParam[]) => {
		const selections: IParam[] = [];
		if (props.singleSelect) {
			if (selected) {
				selections.push(record);
			}
		} else {
			selections.push(...selectedRows);
		}
		emit('selectionChange', selections);
	},
	onSelectAll: (selected: boolean, selectedRows: IParam[]) => {
		emit('selectionChange', selectedRows);
	},
};
//  行配置项
const customRow = (record: IParam) => {
	return {
		onClick: (event: MouseEvent) => {
			//  开启行编辑不响应单击事件
			if (props.enableRowEdit || record.isGroupItem) {
				return;
			}
			clearTimeout(timer);
			timer = setTimeout(() => {
				emit('rowClick', record, event);
			}, 200);
		},
		onDblclick: (event: MouseEvent) => {
			//  开启行编辑不响应双击事件
			if (props.enableRowEdit || record.isGroupItem) {
				return;
			}
			clearTimeout(timer);
			emit('rowDbClick', record, event);
		},
	};
};
const limit = ref(
	props.paging && props.paging.defaultPageSize
		? props.paging.defaultPageSize
		: 20
);
const currentPage = ref(props.current ? props.current : 1);
const currentSort = ref({ sortField: '', sortDir: 'ascend' });

//  表格滚动配置项
const scrollOptions = ref({
	scrollToFirstRowOnChange: true,
	x: '100%',
	y: '100%',
});

//  处理切换列宽
const handleResizeColumn = (width: number, col: IParam) => {
	col.width = width;
};

const handleGridChange = (
	pagination: IParam,
	filters: IParam,
	sorter: IParam,
	data: IParam
) => {
	//  分页变化
	if (pagination) {
		if (pagination.current !== currentPage.value) {
			currentPage.value = pagination.current;
			emit('pageChange', currentPage.value);
			return;
		}
		if (pagination.pageSize !== limit.value) {
			limit.value = pagination.pageSize;
			emit('pageSizeChange', limit.value);
			return;
		}
	}
	//  排序变化
	if (sorter) {
		const { field, order } = sorter;
		if (
			field !== currentSort.value.sortField ||
			order !== currentSort.value.sortDir
		) {
			currentSort.value = { sortDir: order, sortField: field };
			emit(
				'sortChange',
				field,
				order === 'ascend' ? 'asc' : order === 'descend' ? 'desc' : ''
			);
		}
	}
};

const handleAction = (detail: IParam, data: IParam, event: MouseEvent) => {
	emit('actionClick', detail.logic, data, event);
};
</script>
